from django.shortcuts import render
from rest_framework.views import APIView, Response
from django.forms.models import model_to_dict
from rest_framework.viewsets import ModelViewSet
from web import models
import hashlib
import mistune
from web.serializers import *

# md5加盐
SALT = b'yangye'


# 初始化密码
def init_password(password):
    md5obj = hashlib.md5(SALT)
    md5obj.update(password.encode("utf-8"))
    passwd = md5obj.hexdigest()
    return passwd


# Create your views here.
# 初始化返回数据
def init_data(iscode, data, msg=''):
    if iscode:
        data = {
            'code': 0,
            'data': data,
            'msg': '成功' if msg == '' else msg
        }
        return data

    else:
        data = {
            'code': 1,
            'data': [],
            'msg': '失败' if msg == '' else msg
        }
        return data


# class categoryView(APIView):
#     def post(self, request):
#         category_list = models.category.objects.filter()
#         # 列表生成表达式
#         data = [model_to_dict(category_item) for category_item in category_list]
#         return Response(init_data(True, data))
#
#     def get(self, request):
#         category_list = models.category.objects.filter()
#         # 列表生成表达式
#         data = [model_to_dict(category_item) for category_item in category_list]
#         return Response(init_data(True, data))


class loginView(APIView):
    def post(self, response):
        print(response.data)
        data = {
            'token': '123456'
        }
        return Response(init_data(True, data))


class userView(APIView):
    def get(self, response):
        token = response.query_params.get('token')
        userlist = models.author.objects.all()
        for user in userlist:
            print('user',user)
        print('token', token)
        data = {
            'roles': ['admin'],
            'introduction': 'I am a super administrator',
            'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            'name': 'Super Admin'
        }
        return Response(init_data(False, data))

class logoutView(APIView):
    def post(self, request):
        print('request', request)
        data = {}
        return Response(init_data(True, data))

class categoryView(APIView):
    def get(self, response):
        category_list = models.category.objects.all()
        info = categorySerializers(instance=category_list, many=True)
        print('info',info)
        return Response(init_data(True, info.data))
        # ser = categorySerializers()


class authorView(APIView):
    def post(self, request):
        data = request.data
        user = data.get('username', None)
        if not user:
            return Response(init_data(False, {}, '请输入用户名'))
        phone = data.get('phone', None)
        if not phone:
            return Response(init_data(False, {}, '请输入手机号'))
        if len(phone) != 11:
            return Response(init_data(False, {}, '手机号输入有误'))
        password = data.get('password', None)
        if not user:
            return Response(init_data(False, {}, '请输入密码'))
        isadd = True if len(models.author.objects.filter(phone=phone)) == 0 else False
        if not isadd:
            return Response(init_data(False, {}, '手机号已注册'))
        new_user = models.author()
        new_user.name = user
        new_user.phone = phone
        new_user.password = init_password(password)
        new_user.save()
        return Response(init_data(True, {}, '成功'))


class articleView(APIView):
    def post(self, request):
        data = request.data
        title = data.get('title', None)
        content = data.get('content', None)
        author = data.get('author', None)
        category = data.get('category', None)
        article = models.article()
        article.title = title
        article.content = content
        author_obj = models.author.objects.filter(id=author)[0]
        article.author = author_obj
        article.save()
        for i in eval(category):
            category_item = models.category.objects.filter(id=i)[0]
            # 添加多个分类 多对对添加前需已经保存
            article.category.add(category_item)
        return Response(init_data(True, {}))

    def get(self, request):
        data = request.query_params
        id = data.get('id', None)
        if not id:
            article_list = models.article.objects.all()
            ser_list = articleSerializers(article_list, many=True)
            list = []
            for i in ser_list.data:
                content = i.get('content')
                content = mistune.markdown(content)
                i['content'] = content
                list = [*list, i]
                print(content)
            return Response(init_data(True, list))
        article_info = models.article.objects.filter(id=id).first()
        info = articleSerializers(article_info).data
        content = info.get('content')
        info['content'] = mistune.markdown(content)
        if not article_info:
            return Response(init_data(False, {}, '查询不到文章'))
        return Response(init_data(True, info))


class category_article(APIView):
    def get(self, resquest):
        data = resquest.query_params
        category_id = data.get('category_id')
        info = models.category.objects.filter(id=category_id).first()
        article_list = models.article.objects.filter(category=info.id)
        print(article_list)
        if not info:
            print(info)
        category_info = categorySerializers(info)
        return Response(init_data(True, {category_info.data}))

    def post(self, resquest):
        print(resquest)
